package main

import (
	"flag"
	"fmt"
	"goADS"
	"os"
	"os/signal"
	"sync"
	"syscall"
	//"time"

	log "github.com/cihub/seelog"
	//    "bytes"
	//    "encoding/hex"
	//    "encoding/binary"
)

var WaitGroup sync.WaitGroup

func main() {
	defer log.Flush()

	// Flags
	debug := flag.Bool("debug", false, "print debugging messages.")
	ip := flag.String("ip", "192.168.3.7", "the address to the AMS router")
	netid := flag.String("netid", "192.168.3.7.1.1", "AMS NetID of the target")
	port := flag.Int("port", 801, "AMS Port of the target")

	flag.Parse()
	fmt.Println(*debug, *ip, *netid, *port)

	// Start the logger/
	logger, err := log.LoggerFromConfigAsFile("logconfig.xml")
	if err != nil {
		panic(err)
	}

	log.ReplaceLogger(logger)
	goADS.UseLogger(logger)

	if !*debug {
		logger.Close()
	}

	connection, e := goADS.NewConnection(*ip, *netid, *port)
	//自定义soucenetid
	connection.SetSoureNetid("172.16.1.8")
	connection.Connect()

	defer connection.Close() // Close the connection when we are done
	if e != nil {
		logger.Critical(e)
		os.Exit(1)
	}
	// Add a handler for Ctrl^C,  soft shutdown
	go shutdownRoutine(*connection)

	// data, e := connection.ReadDeviceInfo()
	// if e != nil {
	// 	log.Critical(e)
	// 	os.Exit(1)
	// }
	// log.Infof("Successfully conncected to \"%s\" version %d.%d (build %d)", data.DeviceName, data.MajorVersion, data.MinorVersion, data.BuildVersion)

	symbols, _ := connection.UploadSymbolInfo()
	// for _, symbol := range symbols {
	// 	symbol.Walk()
	// }
	log.Warn("Count: ", len(symbols))

	fmt.Println("根据名称取值，MAIN.PLCVAR的值为：" + connection.Value("MAIN.PLCVAR"))
	fmt.Println("根据名称取值，MAIN.TOGGEL的值为：" + connection.Value("MAIN.TOGGEL"))
	fmt.Println("根据名称取值，MAIN.TP_1的值为：" + connection.Value("TP_1.IN"))

	// connection.Set("MAIN.PLCVAR", "100")

	select {}
	WaitGroup.Wait()
	connection.Wait()
	log.Info("MAIN Done :)")
}

func shutdownRoutine(conn goADS.Connection) {
	sigchan := make(chan os.Signal, 2)
	signal.Notify(sigchan, os.Interrupt)
	signal.Notify(sigchan, syscall.SIGTERM)
	<-sigchan

	conn.Close()
}
